package com.ruoyi.system.service.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.Order;
import com.ruoyi.system.mapper.SysDictDataMapper;
import com.ruoyi.system.service.IOrderService;
import com.ruoyi.system.service.ISysDictDataService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.TTablesMapper;
import com.ruoyi.system.domain.TTables;
import com.ruoyi.system.service.ITTablesService;
import org.springframework.transaction.annotation.Transactional;

import static com.ruoyi.common.utils.StringUtils.*;

/**
 * 棋牌室桌子信息Service业务层处理
 *
 * @author ruoyi
 * @since  2025-09-24
 */
@Service
@RequiredArgsConstructor
public class TTablesServiceImpl extends ServiceImpl<TTablesMapper ,TTables> implements ITTablesService
{
    private final TTablesMapper tTablesMapper;
    private final IOrderService orderService;
    private final ISysDictDataService sysDictDataMapper;

    /**
     * 查询棋牌室桌子信息
     *
     * @param uuid 棋牌室桌子信息主键
     * @return 棋牌室桌子信息
     */
    @Override
    public TTables selectTTablesByUuid(String uuid)
    {
        if (isEmpty(uuid)){
            throw new ServiceException("导入会员数据不能为空！");
        }
        return tTablesMapper.selectById(uuid);
    }

    /**
     * 查询棋牌室桌子信息列表
     *
     * @param tTables 棋牌室桌子信息
     * @return 棋牌室桌子信息
     */
    @Override
    public List<TTables> selectTTablesList(TTables tTables) throws ParseException {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<TTables> list = tTablesMapper.selectTTablesList(tTables);
        for (TTables t:list){
            if(StringUtils.isNotNull(t.getBeginTime())){
                Date nowDate = DateUtils.getNowDate();
              t.setTime(convertSecondsToTimeFormat(getTime(df.format(t.getBeginTime()), df.format(nowDate))));
                LocalDateTime startTime = LocalDateTime.parse(df.format(t.getBeginTime()), formatter);
                LocalDateTime endTime = LocalDateTime.parse(df.format(DateUtils.getNowDate()), formatter);
                Duration duration = Duration.between(startTime, endTime);
                if (duration.isNegative()) {
                    throw new RuntimeException("请稍后重试...");
                }

                long totalMinutes = duration.toMinutes();
                BigDecimal minutesPerHour = BigDecimal.valueOf(60);

                BigDecimal pricePerMinute = t.getPrice().divide(minutesPerHour, 2, RoundingMode.HALF_UP);
                // 向上取整到整数
               t.setTotalPrice( pricePerMinute.multiply(BigDecimal.valueOf(totalMinutes)).setScale(0, RoundingMode.CEILING));

            }
        }
        return list;
    }

    /**
     * 新增棋牌室桌子信息
     *
     * @param tTables 棋牌室桌子信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertTTables(TTables tTables)
    {
        return  this.baseMapper.insert(tTables);
    }

    /**
     * 修改棋牌室桌子信息
     *
     * @param tTables 棋牌室桌子信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateTTables(TTables tTables)
    {
        if(isEmpty(tTables.getUuid())){
            throw new RuntimeException("主键标识不能为空");
        }
        //开台
        if ("1".equals(tTables.getStatus())){
            TTables t = tTablesMapper.selectById(tTables.getUuid());
            //判断是否已经预定了,预定时也要算金额
            if (StringUtils.isNotNull(t.getBeginTime())){
                tTables.setBeginTime(t.getBeginTime());
            }else {
                tTables.setBeginTime(DateUtils.getNowDate());
            }
        }
        //预定
        if ("2".equals(tTables.getStatus())){
            tTables.setBeginTime(DateUtils.getNowDate());
        }
        //结算
        if ("3".equals(tTables.getStatus())){
            //普通人结算 无会员信息
            if ("微信/支付宝".equals(tTables.getItem())||"现金".equals(tTables.getItem())){
                Order order = new Order();
                order.setIsMember("N");
                order.setPrice((long) Integer.parseInt(tTables.getTotalPrice().toString()));
                order.setMethod(sysDictDataMapper.selectDictValue("method",tTables.getItem()));
                order.setRemark(tTables.getRemark());
                orderService.insertOrder(order);
            }else{
                Order order = new Order();
                order.setIsMember("Y");
                order.setPrice((long) Integer.parseInt(tTables.getTotalPrice().toString()));
                order.setMethod(sysDictDataMapper.selectDictValue("method",tTables.getItem()));
                order.setRemark(tTables.getRemark());
                orderService.insertOrder(order);
            }
                tTables.setBeginTime(null);
                tTables.setTotalPrice(null);
                tTables.setTime(null);

        }
        return this.baseMapper.updateById(tTables);
    }


    /**
     * 删除棋牌室桌子信息信息
     *
     * @param uuid 棋牌室桌子信息主键
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int deleteTTablesByUuid(String uuid)
    {
        return  this.baseMapper.deleteById(uuid);
    }
    private  int getTime(String startTime, String endTime) throws ParseException {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long eTime = df.parse(endTime).getTime();
        long sTime = df.parse(startTime).getTime();
        return Math.toIntExact((eTime - sTime) / 1000);
    }
    /**
     * 将秒数转换为时分秒的格式。
     *
     * @param seconds 秒数，整型数值
     * @return 返回时分秒格式的字符串，如"02:23:45"
     */
    private  String convertSecondsToTimeFormat(int seconds) {
        int hours = seconds / 3600; // 计算小时数
        int remainder = seconds % 3600; // 计算剩余秒数
        int minutes = remainder / 60; // 计算分钟数
        seconds = remainder % 60; // 计算剩余秒数
        return String.format("%02d小时%02d分钟%02d秒", hours, minutes, seconds);
    }
}
